Question:
Implement Sort Function on array(POSITIVE INTEGER) based on following condition
a) EVERY EVEN NUMBER IS SORTED IN ASCENDING ORDER
b) EVERY ODD NUMBER IS SORTED IN DESCENDING ORDER
(In output array even numbers should be before odd numbers)
SAMPLE OUTPUT: [2,4,6,8,9,7,5,3,1]
Before seeing the solution think of one thing when 10 is less than 5
Answer is if 10 is negative (-10<5)
So, in this question I have used two basic fundamental things for solving
- Concept of Number System
- No such number can be present in an array greater than summation of those absolute(numbers)
For solving above question :
Let's Say array is {1,5,2,8,9,6}
- Multiply -1 with all odd numbers present in the array
- array is {-1,-5,2,8,-9,6}
- Sort in Ascending order
- array is {-9,-5,-1,2,6,8}
- Do summation of all elements in array and store the value in variable
- total_sum=31
- We know in that array right most number is highest even number and left most number is highest odd number(ignoring sign).So store highest even number in another varible
- highest_even=8
- No add total_sum with all the number which is less than 0(odd)
- array is {22,26,30,2,6,8}
- Sort in Ascending Order
- array is {2,6,8,22,26,30}
- Now numbers which is greater than highest_even ,do subtraction from total_num
- array is {2,6,8,9,5,1}
Congratulations!!!We found out our solution
Here is the Java Code:
import java.util.*;
public class OddEven {
public void logic(int arr[]) {
int total=0;
//negative multiplication
for(int i=0;i<arr.length;i++) {
if(arr[i]%2!=0)
arr[i]*=-1;
//doing summation
total+=Math.abs(arr[i]);
}
//first sort
Arrays.sort(arr);
//storing largest even
int check=arr[arr.length-1];
//doing addition with odd
for(int i=0;i<arr.length;i++) {
if(arr[i] <0) {
arr[i]+=total;
}
}
//second sort
Arrays.sort(arr);
//doing subtraction
for(int i=0;i<arr.length;i++) {
if(arr[i]>check)
arr[i]=total-arr[i];
}
//here is the result
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
OddEven obj=new OddEven();
int arr[] = { 1, 3, 2, 7, 5, 4,9,80,99,11 };
obj.logic(arr);
}
}
OUTPUT: [2, 4, 80, 99, 11, 9, 7, 5, 3, 1]
Time Complexity of this solution is O(nlogn)
~😀😀😀HAPPY CODING😀😀😀~
Post a Comment
Post a Comment
You are welcome to share your thoughts with us!